﻿#include "Logger.h"

bool Logger::init(LogLevel level, LogOutputMode mode, const std::string &fileName)
{
    if (_initialized)
    {
        return true; // 避免重复初始化
    }

    _logLevel = level;
    _outputMode = mode;

    if (_outputMode == FILEOUT)
    {
        if (fileName.empty())
        {
            std::cerr << "Error: File name is required for FILE output mode." << std::endl;
            return false;
        }
        _logFile.open(fileName, std::ios::out | std::ios::app);
        if (!_logFile.is_open())
        {
            std::cerr << "Error: Failed to open log file: " << fileName << std::endl;
            throw std::runtime_error("Failed to open log file: " + fileName);
        }
    }
    _initialized = true;
    return true;
}

void Logger::log(LogLevel level, const std::string &levelStr, const std::string &msg)
{
    if (level < _logLevel)
        return; // 忽略低于当前日志级别的日志

    std::lock_guard<std::mutex> guard(_logMutex);

    // 获取当前时间
    std::time_t now = std::time(0);
    std::tm timeInfo;
#if defined(_WIN32)
    localtime_s(&timeInfo, &now); // Windows
#else
    localtime_r(&now, &timeInfo); // Linux/macOS
#endif
    std::ostringstream timeStream;
    timeStream << (timeInfo.tm_year + 1900) << "-" << (timeInfo.tm_mon + 1) << "-"
               << timeInfo.tm_mday << " " << timeInfo.tm_hour << ":" << timeInfo.tm_min << ":"
               << timeInfo.tm_sec;

    std::string timeStr = timeStream.str();

    // 输出到控制台
    if (_outputMode == CONSOLE)
    {
        std::cout << "[" << timeStr << "] [" << levelStr << "] " << msg << std::endl;
    }
    // 输出到文件
    else if (_outputMode == FILEOUT && _logFile.is_open())
    {
        _logFile << "[" << timeStr << "] [" << levelStr << "] " << msg << std::endl;
    }
}
